package org.tinygroup.tinyscript.springmvc;

import java.util.ArrayList;
import java.util.List;

import org.springframework.http.MediaType;
import org.springframework.web.servlet.ModelAndView;
import org.tinygroup.commons.tools.StringUtil;
import org.tinygroup.tinyscript.mvc.ControllerContext;
import org.tinygroup.tinyscript.mvc.ConvertHandler;
import org.tinygroup.tinyscript.mvc.ResponseWrapper;

@SuppressWarnings("rawtypes")
public class AcceptResponseWrapper implements ResponseWrapper<ModelAndView>{

	private List<ConvertHandler>  handerList = new ArrayList<ConvertHandler>();

	public List<ConvertHandler> getHanderList() {
		return handerList;
	}

	public void setHanderList(List<ConvertHandler> handerList) {
		this.handerList = handerList;
	}

	@SuppressWarnings("unchecked")
	public ModelAndView wrap(ControllerContext context, Object value)
			throws Exception {
		MediaType[] mediaTypes = getMediaTypes(context);
		for(MediaType mediaType:mediaTypes){
			for(ConvertHandler handler:handerList){
				if(handler.isMatch(value, mediaType)){
				   handler.convert(context.getResponse(), value, mediaType);
				   return null;
				}
			}
		}
		return null;
	}
	
	protected MediaType[] getMediaTypes(ControllerContext context){
		String acceptStr = (String)context.get("Accept");
		if(StringUtil.isEmpty(acceptStr)){
		   return new MediaType[]{MediaType.ALL};
		}
		String[] accepts = acceptStr.split(",");
		MediaType[] mediaTypes = new MediaType[accepts.length];
		for(int i=0;i<accepts.length;i++){
			mediaTypes[i] = MediaType.valueOf(accepts[i]);
		}
		return mediaTypes;
	}

}
